#include <stdio.h>

int findInsertPosition(float array[], int length, int target) {
    int left = 0, right = length - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (array[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return left; // 目标应插入的位置
}

/**
 * @brief Get the fitting object
 * 根据数组x与数组y的映射关系，根据输入值进行拟合获取输出。
 *
 * @param target
 * @param x
 * @param y
 * @param array_len
 * @return float
 */
float get_fitting(float input, float x[], float y[], int array_len) {
    float output = 0.0f;
    if (input < x[0]) {
        output = y[0];
    } else if (input > x[array_len - 1]) {
        output = y[array_len - 1];
    }

    int right = findInsertPosition(x, array_len, input);
    int left  = right - 1;

    float slope = (y[right] - y[left]) / (x[right] - x[left]);
    output      = y[left] + slope * (input - x[left]);

    return output;
}

int main() {
    float pitch[]    = {2, 4, 6, 8, 10, 12, 14};
    float throttle[] = {0.11, 0.2, 0.32, 0.4, 0.56, 0.6, 0.7};

    int length = sizeof(pitch) / sizeof(pitch[0]);
    int target = 7;

    // int result = binarySearch(arr, length, target);
    int result = findInsertPosition(pitch, length, target);

    if (result != -1) {
        printf("元素 %d 的索引是 %d\n", target, result); // 输出：元素 10 的索引是 4
    } else {
        printf("元素未找到\n");
    }

    // int right = result;
    // int left  = result - 1;

    // float slope  = (throttle[right] - throttle[left]) / (pitch[right] - pitch[left]);
    // float output = throttle[left] + slope * (target - pitch[left]);

    // float output = get_fitting(target, pitch, throttle, length);
    // printf("output=%.2f\n", output);

    return 0;
}